package com.example.cloud.service.basic.info.impl;

import com.example.cloud.dao.basic.info.HomeProductRepository;
import com.example.cloud.dao.mongdb.basic.info.MongoHomeProductRepository;
import com.example.cloud.model.basic.HomeProduct;
import com.example.cloud.service.basic.info.HomeProductService;
import com.example.cloud.utils.BusinessUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.Transactional;
import java.util.List;

/**
 * Created by wangtao on 2018/6/6.
 */
@Service
public class HomeProductServiceImpl implements HomeProductService {

    private static final Logger logger = Logger.getLogger(HomeProductServiceImpl.class);

    @PersistenceContext
    EntityManager em;

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    private HomeProductRepository homeProductRepository;

    @Autowired
    private MongoHomeProductRepository mongoHomeProductRepository;

    @Override
    @Transactional
    public HomeProduct doSave(HomeProduct record) {
        // 物理保存
        BusinessUtil.appendRecord(record);
        record = homeProductRepository.save(record);
        // 同步缓存
        mongoHomeProductRepository.save(record);
        return record;
    }

    @Override
    public List<HomeProduct> findBasicPlanFromCache(Long homeId) {
        return mongoHomeProductRepository.findByHomeIdAndPlanTypeAndDeleteFlag(homeId, 1, 0);
    }

    @Override
    @Transactional
    public void batchInsert(List<HomeProduct> records) {
        for (int i = 0; i < records.size(); i++) {
            HomeProduct record = records.get(i);
            BusinessUtil.appendRecord(record);
            em.merge(record);
            if (i % 20 == 0) {
                em.flush();
                em.clear();
            }
        }
        mongoHomeProductRepository.save(records);
    }

    @Override
    @Transactional
    public void doDelete(List<Long> ids) {
        // 逻辑删除
        StringBuilder sql = new StringBuilder("update basic_home_product set delete_flag = 1 where id in(:ids)");
        Query query = em.createNativeQuery(sql.toString());
        query.setParameter("ids", ids);
        query.executeUpdate();
        // 删除缓存
        mongoHomeProductRepository.deleteByIdIn(ids);
    }

    @Override
    public void loadCache() {
        List<HomeProduct> list = homeProductRepository.findAll();
        if (!list.isEmpty()) {
            mongoHomeProductRepository.save(list);
            logger.info("*******************家庭病房基本/可选方案产品已全部同步缓存*******************");
        }
    }
}
